﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;

namespace Utils.APIClient
{
    public class LinuxTimestampConverter : IsoDateTimeConverter
    {

        private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var nullable = (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Nullable<>));
            if (reader.TokenType == JsonToken.Null && nullable == false)
            {
                return null;
            }
            if (reader.TokenType == JsonToken.Integer)
            {
                if (reader.Value is long timeSpan)
                {
                    var dt = Jan1st1970.AddSeconds(timeSpan).ToLocalTime();
                    return dt;
                }
            }
            else if (reader.TokenType == JsonToken.String)
            {
                long timeSpan;
                if (long.TryParse(reader.Value.ToString(), out timeSpan))
                {
                    var dt = Jan1st1970.AddSeconds(timeSpan).ToLocalTime();
                    return dt;
                }
            }
            return base.ReadJson(reader, objectType, existingValue, serializer);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is DateTime dateTime)
            {
                var timeSpan = (long)(dateTime.ToUniversalTime() - Jan1st1970).TotalSeconds;
                writer.WriteValue(timeSpan);
            }
            else if (value is DateTimeOffset dateTimeOffset)
            {
                var timeSpan = (long)(dateTimeOffset - Jan1st1970).TotalSeconds;
                writer.WriteValue(timeSpan);
            }
            else
            {
                base.WriteJson(writer, value, serializer);
            }
        }
    }
}
